package com.briup.estore.web.filter;

import com.briup.estore.bean.Customer;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 验证登陆信息
 */
@WebFilter("/addBookToShopCart")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;
        HttpSession session=req.getSession();
        Customer user =(Customer) session.getAttribute("user");
        //如果存在，直接放行
        if(user != null){
            filterChain.doFilter(req,resp);
            return;
        }
        //分析cookie里面又没有（登陆成功之后记得也往cookie里放一份）
        Cookie[] cookies=req.getCookies();
        for(Cookie c:cookies){
            if("userId".equals(c.getName())){
                req.setAttribute("userId",c.getValue());
                filterChain.doFilter(req,resp);
                return;
            }
        }
        session.setAttribute("msg","请您登陆后再操作！");
        //跳转页面
        resp.sendRedirect("login") ;

    }

    @Override
    public void destroy() {

    }
}
